package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.GoodsEvaluateEnum;
import com.frogs.system.util.UserTypeEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.GoodsEvaluateCommentDao;
import com.frogs.ucenter.entity.GoodsEvaluateComment;
import com.frogs.ucenter.entity.GoodsEvaluateCommentInfo;
import com.frogs.ucenter.entity.GoodsEvaluateInfo;
import com.frogs.ucenter.util.DataCacheKey;
import com.frogs.ucenter.v1.request.GoodsEvaluateCommentAddRequest;
import com.frogs.ucenter.v1.request.GoodsEvaluateCommentDeleteRequest;
import com.frogs.ucenter.v1.request.GoodsEvaluateCommentListRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DeleteResponse;
import com.frogs.ucenter.v1.response.GoodsEvaluateCommentListResponse;
import com.frogs.ucenter.v1.service.GoodsEvaluateCommentService;
import com.frogs.ucenter.v1.util.ApiConstants;

/**
 *
 * @author lijian
 * @version 2014年3月21日 - 下午4:15:16
 */
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"goodsEvaluateCommentService")
public class GoodsEvaluateCommentServiceImpl extends GoodsEvaluateBaseServiceImpl implements GoodsEvaluateCommentService {
    
	private static final Logger log = LoggerFactory.getLogger(GoodsEvaluateCommentServiceImpl.class);
	
	@Resource
    private GoodsEvaluateCommentDao goodsEvaluateCommentDao;
	
    /**
     * 添加商品评价评论
     * @param request
     * @return
     */
    @Override
    public Response addGoodsEvaluateCommentInfo(Request request) throws Exception {
    	AddResponse<GoodsEvaluateComment> response = new AddResponse<GoodsEvaluateComment>();
    	try {
    		GoodsEvaluateCommentAddRequest evaluateCommentAddRequest = (GoodsEvaluateCommentAddRequest)request;
    		GoodsEvaluateComment goodsEvaluateComment = this.insertEvaluateComment(evaluateCommentAddRequest);
    		response.setInfo(goodsEvaluateComment);
    	} catch (Exception e) {
    		log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
    	}
    	return response;
    }
    
    private GoodsEvaluateComment insertEvaluateComment(GoodsEvaluateCommentAddRequest evaluateCommentAddRequest) {
    	GoodsEvaluateComment goodsEvaluateComment = new GoodsEvaluateComment();
		goodsEvaluateComment.setUserId(evaluateCommentAddRequest.getUserId());
		goodsEvaluateComment.setGoodsEvaluateId(evaluateCommentAddRequest.getGoodsEvaluateId());
		goodsEvaluateComment.setOriginalGoodsId(evaluateCommentAddRequest.getOriginalGoodsId());
		goodsEvaluateComment.setGoodsId(evaluateCommentAddRequest.getGoodsId());
		goodsEvaluateComment.setMealId(evaluateCommentAddRequest.getMealId());
		goodsEvaluateComment.setContent(evaluateCommentAddRequest.getContent());
		goodsEvaluateComment.setParentCommentId(evaluateCommentAddRequest.getParentCommentId());
		goodsEvaluateComment.setParentCommentUserId(evaluateCommentAddRequest.getParentCommentUserId());
		goodsEvaluateComment.setParentCommentNickName(evaluateCommentAddRequest.getParentCommentNickName());
		goodsEvaluateComment.setApplicablePlatformId(evaluateCommentAddRequest.getApplicablePlatformId());
		goodsEvaluateComment.setStatus(GoodsEvaluateEnum.AUDITED_PASS.getId());
		goodsEvaluateCommentDao.insert(goodsEvaluateComment);
		StringBuilder  mapKey = new StringBuilder();
		mapKey.append(DataCacheKey.goodsEvaluateCommentMapKey).append("_GOODSEVALUATEID_").append(evaluateCommentAddRequest.getGoodsEvaluateId());
		cache.remove(mapKey.toString());
		// 评论采集日志
		StringBuilder sb = new StringBuilder();
		sb.append(evaluateCommentAddRequest.getUserId()).append("`");
		sb.append("评论").append("`");
		sb.append(evaluateCommentAddRequest.getGoodsId()).append("`");
		sb.append(evaluateCommentAddRequest.getMealId()).append("`");
		sb.append(goodsEvaluateComment.getCreateTime()).append("`");
		log.info(sb.toString());
		return goodsEvaluateComment;
    }
    
    /**
	 * 删除商品评价
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Response deleteGoodsEvaluateCommentInfo(Request request) throws Exception{
		DeleteResponse response = new DeleteResponse();
		try {
			GoodsEvaluateCommentDeleteRequest goodsEvaluateDeleteRequest = (GoodsEvaluateCommentDeleteRequest)request;
			Integer userId = goodsEvaluateDeleteRequest.getUserId();
			Integer goodsEvaluateCommentId = goodsEvaluateDeleteRequest.getGoodsEvaluateCommentId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", goodsEvaluateCommentId);
			params.put("eqUserId", userId);
			params.put("status", GoodsEvaluateEnum.DELETED.getId());
			int count = goodsEvaluateCommentDao.updateByMap(params);
			if (count > 0) {
				GoodsEvaluateComment evaluateComment = goodsEvaluateCommentDao.selectById(goodsEvaluateCommentId);
				StringBuilder  mapKey = new StringBuilder();
				mapKey.append(DataCacheKey.goodsEvaluateCommentMapKey).append("_GOODSEVALUATEID_").append(evaluateComment.getGoodsEvaluateId());
				cache.remove(mapKey.toString());
				response.setCode(ApiResultEnum.SUCCESS.getId());
			}
			else{
				response.setCode(ApiResultEnum.FAIL.getId());
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 获取商品评价评论列表
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Response getGoodsEvaluateCommentList(Request request) throws Exception{
		GoodsEvaluateCommentListResponse response = new GoodsEvaluateCommentListResponse();
		try {
			GoodsEvaluateCommentListRequest commentListRequest = (GoodsEvaluateCommentListRequest) request;
			Integer goodsEvaluateId = commentListRequest.getGoodsEvaluateId();
			Integer pageNo = commentListRequest.getPageNum();
			Integer pageSize = commentListRequest.getNumPerPage();
			Map<String, Object> cacheEvaluteComment = new HashMap<String, Object>();
			StringBuilder  mapKey = new StringBuilder();
			mapKey.append(DataCacheKey.goodsEvaluateCommentMapKey).append("_GOODSEVALUATEID_").append(goodsEvaluateId);
			cacheEvaluteComment = (Map<String, Object>) cache.get(mapKey.toString());
			GoodsEvaluateInfo evaluateInfos = new GoodsEvaluateInfo();
			Map<String, Object> obj = new HashMap<String, Object>();
			String key = "_" + pageNo + "_" + pageSize;
			if (cacheEvaluteComment != null) {
				obj = (Map<String, Object>) cacheEvaluteComment.get(key);
				if(obj != null) {
					evaluateInfos = (GoodsEvaluateInfo) obj.get("evaluateInfos");
					if (evaluateInfos != null) {
						response.setPageTurn( (PageTurn)obj.get("pageTurn"));
						response.setGoodsEvaluateCommentList(evaluateInfos);
						return response;
					}
				}
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", goodsEvaluateId);
			PageList<Map<String, Object>> list = goodsEvaluateDao.selectAndUserByMap(params, 1, 1);
			if (list != null && list.size() > 0) {
				Map<String, Object> object = list.get(0);
				if ((Integer) object.get("status") == GoodsEvaluateEnum.AUDITED_PASS.getId()) {
					GoodsEvaluateInfo goodsEvaluateInfo = new GoodsEvaluateInfo();
					goodsEvaluateInfo.setId((Integer) object.get("id"));
					if(object.get("user_id") != null){
						goodsEvaluateInfo.setUserId((Integer) object.get("user_id"));
						goodsEvaluateInfo.setUserName((String) object.get("account_name"));
					}
					if( object.get("original_goods_id") != null)
						goodsEvaluateInfo.setOriginalGoodsId((Integer) object.get("original_goods_id"));
					goodsEvaluateInfo.setGoodsId((Integer) object.get("goods_id"));
					goodsEvaluateInfo.setMealId((Integer) object.get("meal_id"));
					
					goodsEvaluateInfo.setContent((String) object.get("content"));
					
					if(object.get("is_pharmacist_evaluate") != null)
						goodsEvaluateInfo.setIsPharmacistEvaluate((Integer) object.get("is_pharmacist_evaluate"));
					goodsEvaluateInfo.setReceivedSeveral((Integer) object.get("received_several"));
					goodsEvaluateInfo.setCreateTime((Date) object.get("create_time"));
					goodsEvaluateInfo.setTag((String) object.get("tag"));
					goodsEvaluateInfo.setBuyTime((Date) object.get("buy_time"));
					
					if(object.get("useful_number") != null)
						goodsEvaluateInfo.setUsefulNumber((Integer) object.get("useful_number"));
					
					if(object.get("praise") != null)
						goodsEvaluateInfo.setPraise((Integer) object.get("praise"));
					
					if(object.get("trample") != null)
						goodsEvaluateInfo.setTrample((Integer) object.get("trample"));
					goodsEvaluateInfo.setNickName((String) object.get("nick_name"));
					goodsEvaluateInfo.setHeadImageUrl((String) object.get("head_image_url"));
					if (object.get("user_type") != null) {
						goodsEvaluateInfo.setUserType((Integer) object.get("user_type"));
						goodsEvaluateInfo.setUserTypeName(UserTypeEnum.getByType((Integer) object.get("user_type")).getName());
					} else {
						goodsEvaluateInfo.setUserType(UserTypeEnum.GENERAL.getType());
						goodsEvaluateInfo.setUserTypeName(UserTypeEnum.getByType(UserTypeEnum.GENERAL.getType()).getName());
					}
					if (object.get("score") != null)
						goodsEvaluateInfo.setScore((Integer) object.get("score"));
					PageList<GoodsEvaluateCommentInfo> commentlist = this.getGoodsEvaluateCommentList((Integer) object.get("id"), pageNo, pageSize);
					goodsEvaluateInfo.setGoodsEvaluateCommentList(commentlist);
					goodsEvaluateInfo.setCommentCount(list.size());
					PageTurn pageTurn = list.getPageTurn();
					response.setPageTurn(pageTurn);
					response.setGoodsEvaluateCommentList(goodsEvaluateInfo);
					obj = new HashMap<String, Object>();
					obj.put("evaluateInfos", evaluateInfos);
					obj.put("pageTurn",pageTurn);
					cacheEvaluteComment.put(key, obj);
					cache.put(mapKey.toString(), cacheEvaluteComment, cacheLifeCycle);
				}
			}
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
}